<?php
namespace tjsd\mappers;

/**
 * Index mapping values to their XML structure.
 * 
 * Every value is stored in <leaf> element in structure of <branch> elements. Every
 * level represents one element of path.
 * 
 * @author Jakub Tesárek <info@tjsd.cz>
 * @copyright 2012
 * @version 1.0
 */
class XmlFileIndex extends \tjsd\core\Object implements Index {
	
	/**
	 * @var SimpleXMLElement	loaded XML structure of index file
	 */
	protected $xmlDocument;
	
	/**
	 *
	 * @param type $file 
	 */
	public function __construct($file) {
		$this->xmlDocument = simplexml_load_file($file);
	}
	
	/**
	 * {@inheritdoc}
	 * 
	 * @param array $path	array with identifiers
	 * @return string			value in path or null if nothing found
	 */
	public function find(array $path) {		
		$element = $this->xmlDocument->xpath($this->buildXPath($path));
		if(count($element) == 1) {
			return (string) $element[0];
		} else {
			return null;
		}
	}
	
	/**
	 * Helper method thats build xPath query from given path
	 * 
	 * @param array $path		array with identifiers
	 * @return string				xPath query 
	 */
	private function buildXPath($path) {
		if(is_array($path) && !empty($path)) {
			$xPath = '/trunk';
			$leaf = '/leaf[@name="' . array_pop($path) . '"]';
			foreach($path as $part) {
				$xPath .= '/branch[@name="' . $part . '"]';
			}
			return $xPath . $leaf;
		}
	}
}